import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import MainLayout from '../layouts/MainLayout.vue'
import StudentDashboard from '../views/StudentDashboard.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        title: '登录'
      }
    },
    {
      path: '/',
      component: MainLayout,
      meta: {
        requiresAuth: true
      },
      children: [
        {
          path: 'dashboard',
          name: 'student-dashboard',
          component: StudentDashboard,
          meta: {
            title: '学生仪表板'
          }
        },
        {
          path: 'courses',
          name: 'student-courses',
          component: () => import('../views/StudentCourses.vue'),
          meta: {
            title: '我的课程'
          }
        },
        {
          path: 'grades',
          name: 'student-grades',
          component: () => import('../views/StudentGrades.vue'),
          meta: {
            title: '我的成绩'
          }
        },
        {
          path: 'profile',
          name: 'student-profile',
          component: () => import('../views/StudentProfile.vue'),
          meta: {
            title: '个人资料'
          }
        },
        {
          path: 'grade-analysis',
          name: 'student-grade-analysis',
          component: () => import('../views/StudentGradeAnalysis.vue'),
          meta: {
            title: '成绩分析维度'
          }
        }
      ]
    },
    // 重定向到登录页面
    {
      path: '/:pathMatch(.*)*',
      redirect: '/login'
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title + ' - 学生成绩分析系统'
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    const isAuthenticated = localStorage.getItem('isAuthenticated')
    if (!isAuthenticated) {
      next('/login')
      return
    }
  }

  // 如果已登录且访问登录页面，重定向到仪表板
  if (to.name === 'login') {
    const isAuthenticated = localStorage.getItem('isAuthenticated')
    if (isAuthenticated) {
      next('/dashboard')
      return
    }
  }

  next()
})

export default router
